package com.platform.base.exception;

import com.platform.base.common.dto.Result;
import com.platform.base.utils.Log;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

@ControllerAdvice
public class ExceptionHandle {

    private final String ERROR_INFO = "服务器出错啦";
    /**
     * 校验异常
     * @param request
     * @param cve
     * @return
     */
    /*@ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public Result Handle(HttpServletRequest request, ConstraintViolationException cve) {
        // Log.e(formatRequest(request), cve);
        String msg = ERROR_INFO;
        if (cve.getConstraintViolations() != null
                && cve.getConstraintViolations().size() > 0
                && cve.getConstraintViolations().iterator().hasNext()) {
            ConstraintViolation cv = cve.getConstraintViolations().iterator().next();
            String tmp = cv.getPropertyPath().toString();
            int index = tmp.indexOf('.');
            if (index > 0) {
                msg = cve.getLocalizedMessage().replace(tmp.substring(0, index + 1), "");
            } else {
                msg = cve.getLocalizedMessage();
            }
        }
        return new Result(false, msg);
    }*/

    /*@ExceptionHandler(value = BaseRuntimeException.class)
    @ResponseBody
    public Result Handle(HttpServletRequest request, BaseRuntimeException bre) {
        // Log.e(formatRequest(request), bre);
        return ResultUtil.error(bre.getCode(), bre.getUserTips());
    }

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result Handle(HttpServletRequest request, BaseException be) {
        // Log.e(formatRequest(request), be);
        return ResultUtil.error(be.getCode(), be.getUserTips());
    }*/

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result Handle(HttpServletRequest request, RuntimeException be) {
        Log.e(formatRequest(request), be);
        return new Result(false, be.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result Handle(HttpServletRequest request, Exception e) {
        Log.e(formatRequest(request), e);
        return new Result(false, ERROR_INFO);
    }

    private String formatRequest(HttpServletRequest request) {
        String method = request.getMethod();
        String path = request.getServletPath();
        String userAgent = request.getHeader("user-agent");
        String referer = request.getHeader("referer");
        return String.format("\n%s  %s\n  %s\n  %s\n", method, path, userAgent, referer);
    }
}
